from flask import Response, request, jsonify
from src.video_stream import generate_frames
from src.button_handlers import (
    handle_button1,
    handle_button2,
    handle_button3,
    handle_button4
)
from src.joystick_handler import handle_joystick_data

def init_routes(app):
    """
    初始化所有路由
    """
    @app.route('/')
    def index():
        return """
        <html>
            <head>
                <title>视频流</title>
            </head>
            <body>
                <h1>视频流</h1>
                <img src="/api/webcam/stream" width="640" height="480">
            </body>
        </html>
        """

    @app.route('/api/webcam/stream')
    def video_feed():
        return Response(generate_frames(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

    @app.route('/api/button', methods=['POST'])
    def handle_button():
        button_id = request.args.get('id', type=int)
        state = request.args.get('state', type=str)
        
        if button_id is None:
            return {'status': 'error', 'message': '缺少按钮ID参数'}, 400
            
        if state not in ['0', '1']:
            return {'status': 'error', 'message': '无效的状态值'}, 400
            
        handlers = {
            1: handle_button1,
            2: handle_button2,
            3: handle_button3,
            4: handle_button4
        }
        
        handler = handlers.get(button_id)
        if handler is None:
            return {'status': 'error', 'message': '无效的按钮ID'}, 400
            
        return handler(state)

    @app.route('/api/joystick', methods=['POST'])
    def handle_joystick():
        data = request.get_json()
        if not data:
            return {'status': 'error', 'message': '缺少摇杆数据'}, 400
        return handle_joystick_data(data) 